package com.fj.netty.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author fj
 * @date 2024/1/2 15:06
 */
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        System.out.println("连接到服务器");
                        ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect("127.0.0.1", 6789);
        System.out.println(channelFuture.channel());
        channelFuture.addListener((ChannelFutureListener) future -> {
            System.out.println("连接建立");
            Channel channel = future.channel();
            System.out.println(channel);
//            channel.close();
            new Thread(()->{
                Scanner scanner = new Scanner(System.in);
                while (true){
                    String msg = scanner.nextLine();
                    if ("q".equals(msg)){
                        channel.close();
                        break;
                    }
                    channel.writeAndFlush(msg);
                }
            }).start();
        });
        ChannelFuture closeFuture = channelFuture.channel().closeFuture();
        closeFuture.addListener((ChannelFutureListener) future -> {
            System.out.println("连接断开");
            nioEventLoopGroup.shutdownGracefully();
        });
        System.out.println("");
    }
}
